#include "mainwindow.h"

// 查找本地可用ip
void MainWindow::listLocalIPs(void)
{
    // 获取所有网络接口
    QHostAddress ipAddress ;
    QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
    for (const QNetworkInterface& interface : interfaces)
    {
        // 检查网络接口是否处于启用状态
        if (interface.flags().testFlag(QNetworkInterface::IsUp) &&
            !interface.flags().testFlag(QNetworkInterface::IsLoopBack))
        {
            // 获取网络接口的所有IPv4地址
            QList<QNetworkAddressEntry> entries = interface.addressEntries();
            for (const QNetworkAddressEntry& entry : entries)
            {
                ipAddress = entry.ip();
                if (ipAddress.protocol() == QAbstractSocket::IPv4Protocol)
                {
                    ui->IP_comboBox->addItem(ipAddress.toString());
                }
            }
        }
    }
}

// 保存手动输入的可用ip到选择栏中
void MainWindow::SaveIpToBox()
{
    QString ip = ui->IP_comboBox->currentText();
    // 检查IP地址是否已经存在于组合框中
    int index = ui->IP_comboBox->findText(ip);
    if (index == -1) {
        // 如果IP地址不存在，则添加它
        ui->IP_comboBox->addItem(ip);
    }
}

// 启动TcpServer
bool MainWindow::TcpServerStart(QString IP, int port)
{
    bool listen = TcpServer->listen(QHostAddress(IP), port);

    connect(TcpServer, &QTcpServer::newConnection, this, &MainWindow::onNewConnection);
    return listen;
}

// 客户端连接服务器
void MainWindow::onNewConnection()
{
    TcpSocket = TcpServer->nextPendingConnection();
    if (TcpSocket) {
        // 添加你的处理代码，例如读取数据、发送响应等 TcpServer
        connect(TcpSocket, &QTcpSocket::readyRead, this, &MainWindow::NetWorkReadyRead);
        connect(TcpSocket, &QTcpSocket::disconnected, TcpSocket, &QTcpSocket::deleteLater);
        ui->network_plainTextEdit->insertPlainText(QString("%1").arg("连接成功\n"));
    }
}

// 作为客户端连接服务器
void MainWindow::onTcpSocketConnect(QAbstractSocket::SocketState state)
{
    if (state == QAbstractSocket::ConnectedState)
    {
        msgbox("连接成功");
        SaveIpToBox();
        ui->Lisen_btn->setText("断开连接");
        ui->NetMode_comboBox->setEnabled(false);
    }

    else if (state == QAbstractSocket::UnconnectedState)
    {
        msgbox("断开连接");
    }

    qDebug() << "连接:" << state;
}

// 接收数据
void MainWindow::NetWorkReadyRead()
{
    TcpSocket = qobject_cast<QTcpSocket*>(sender());
    if (TcpSocket)
    {
        QByteArray data = TcpSocket->readAll();
        NetWorkRXTolalCnt += data.size();
        ui->NetRX->setText(QString("RX:%1").arg(NetWorkRXTolalCnt));
        // hex发送
//        NetSendHex
        // 显示时间
        QString text;
        QDateTime currentDateTime = QDateTime::currentDateTime();
        if (ui->NetReceiveShowTime->isChecked() && \
                currentDateTime.toString("yyyy-MM-dd HH:mm:ss") != LastSerialReadTime.toString("yyyy-MM-dd HH:mm:ss"))
        {
            text = QString("%1%2").arg(currentDateTime.toString("yyyy-MM-dd HH:mm:ss #\n")).arg(QString::fromUtf8(data));
            ui->network_plainTextEdit->insertPlainText(text);
            LastSerialReadTime = currentDateTime;
        }
        else
        {
            ui->network_plainTextEdit->insertPlainText(data);
        }
        if (ui->NextWorkFind_checkBox->isChecked())
        {
            ChangeReceivePlainTextEditAllStringColor(ui->network_plainTextEdit);
            ChangeReceivePlainTextEditSubStringColor(ui->network_plainTextEdit, ui->NetWorkFind_lineEdit);
        }
        // 获取滚动条的最大值
        int maximumScroll = ui->network_plainTextEdit->verticalScrollBar()->maximum();
        ui->network_plainTextEdit->verticalScrollBar()->setValue(maximumScroll-10);
        // 滚动到底部
        ui->network_plainTextEdit->verticalScrollBar()->setValue(ui->network_plainTextEdit->verticalScrollBar()->maximum());
    }
}

// 发送数据
void MainWindow::onReadyWrite()
{
    if (!TcpServer->isListening())
    {
        msgbox("请开启监听");
        return;
    }
    if (TcpSocket) {
        QString text = ui->networkSend_plainTextEdit->toPlainText();

        int ret = TcpSocket->write(text.toUtf8());
        NetWorkTXTolalCnt += ret;
        ui->NetTX->setText(QString("TX:%1").arg(NetWorkTXTolalCnt));
    }
    else
        msgbox("发送失败");
}
